<template>
  <!--单船物量信息-->
  <div class="innerBox">
    <div class="search">
      <SearchForm
        ref="searchFormRef"
        :formInputs="state.formInputs"
        @submit="search"
      />
      <a-button @click="onExportExcel" type="primary" link
        ><template #icon>
          <file-excel-outlined />
        </template>
        导出</a-button
      >
    </div>
    <div class="tables">
      <a-table
        size="middle"
        :data-source="state.source"
        :columns="state.columns"
        stripe
        bordered
        :pagination="state.pager"
        :scroll="{ x: 1200 }"
        @change="handleTableChange"
      >
      </a-table>
    </div>
  </div>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, onMounted, toRaw } from "vue";
import _ from "lodash";
import SearchForm from "@/components/SearchForm.vue";
import { planList } from "@/utils/planList";

const { proxy } = getCurrentInstance();

const columns = {
  // 使用材料
  0: [
    {
      title: "供货单位",
      dataIndex: "supplierUnit",
      key: "supplierUnit",
      width: 100,
      ellipsis: true,
    },
    {
      title: "领料部门",
      dataIndex: "pickingDepart",
      width: 120,
      ellipsis: true,
      key: "pickingDepart",
    },
    {
      title: "事务类型",
      dataIndex: "transactionType",
      width: 100,
      ellipsis: true,
      key: "transactionType",
    },
    {
      title: "领用项目编号",
      dataIndex: "projectCode",
      width: 100,
      ellipsis: true,
      key: "projectCode",
    },
    {
      title: "领用项目名称",
      dataIndex: "projectName",
      width: 100,
      ellipsis: true,
      key: "projectName",
    },
    {
      title: "物料编码",
      dataIndex: "materialCode",
      width: 80,
      ellipsis: true,
      key: "materialCode",
    },
    {
      title: "物料名称",
      dataIndex: "materialName",
      width: 120,
      ellipsis: true,
      key: "materialName",
    },
    {
      title: "物料组",
      dataIndex: "materialGroup",
      width: 80,
      ellipsis: true,
      key: "materialGroup",
    },
    {
      title: "发货数量",
      dataIndex: "shippedNum",
      width: 80,
      ellipsis: true,
      key: "shippedNum",
    },
    {
      title: "业务单位",
      dataIndex: "unit",
      width: 80,
      ellipsis: true,
      key: "unit",
    },
    {
      title: "单根重量(KG)",
      dataIndex: "unitWeight",
      width: 80,
      ellipsis: true,
      key: "unitWeight",
    },
    {
      title: "总重量(KG)/容量(L/桶)",
      dataIndex: "totalWeight",
      key: "totalWeight",
      width: 80,
      ellipsis: true,
    },
    {
      title: "采购单位",
      dataIndex: "buyingCom",
      width: 80,
      ellipsis: true,
      key: "buyingCom",
    },
    {
      title: "供应商",
      dataIndex: "supplierCom",
      width: 180,
      ellipsis: true,
      key: "supplierCom",
    },
  ],
  // 使用设备
  1: [
    { title: "供货单位", dataIndex: "supplierUnit", key: "supplierUnit" },
    { title: "使用设备", dataIndex: "machine", key: "machine" },
    { title: "设备型号", dataIndex: "machineCode", key: "machineCode" },
    { title: "数量", dataIndex: "num", key: "num" },
    { title: "单位", dataIndex: "unit", key: "unit" },
    { title: "使用时长", dataIndex: "hours", key: "hours" },
  ],
};

const apis = {
  0: "/material/solid/list",
  1: "/material/machine/list",
};

const state = reactive({
  formInputs: [
    {
      label: "船舶",
      type: "select",
      name: "repairId",
      options: [],
      defaultValue: null,
    },
    {
      label: "部门",
      type: "select",
      name: "departId",
      options: [],
      defaultValue: null,
    },
    {
      label: "物量类型",
      type: "select",
      name: "type",
      options: [
        { label: "使用材料", value: 0 },
        { label: "使用设备", value: 1 },
      ],
      defaultValue: 0,
    },
  ],
  searchObj: {
    repairId: null,
    departId: null,
    type: 0,
  },
  columns: [],
  source: [],
  pager: {
    current: 1,
    pageSize: 12,
    total: 0,
    showSizeChanger: false,
    size: "normal",
  },
});
const searchFormRef = ref();

const search = ({ repairId, departId, type }) => {
  state.searchObj = { repairId, departId, type };
  getList(1);
};

// 获取所有维修船舶
const getShipDict = async () => {
  const { success, data } = await proxy.$axios.get("/ship_repair/dict");
  if (success) {
    const one = _.find(state.formInputs, { name: "repairId" });
    one.options = _.map(data, (o) => ({
      label: o.shipName,
      value: o.repairId,
    }));

    const firstRepairId = data[0].repairId;
    searchFormRef.value.changeFieldValue("repairId", firstRepairId);
    state.searchObj.repairId = firstRepairId;
  }
};

// 获取所有的部门
const getDepts = async () => {
  const { success, data } = await proxy.$axios.get("/department/list");
  if (success) {
    const one = _.find(state.formInputs, { name: "departId" });
    one.options = _.map(data, (o) => ({
      label: o.name,
      value: o.id,
    }));

    const firstId = data[0].id;
    searchFormRef.value.changeFieldValue("departId", firstId);
    state.searchObj.departId = firstId;
  }
};

// 数据翻页
const handleTableChange = ({ current }) => {
  getList(current);
};

const getList = async (page) => {
  const { repairId, departId, type } = state.searchObj;
  state.columns = columns[type];

  const api = apis[type];
  const { success, data } = await proxy.$axios.get(api, {
    params: {
      pageNumber: page,
      pageSize: state.pager.pageSize,
      shipRepairId: repairId,
      departId,
    },
  });
  if (success) {
    const { content, totalElements } = data;
    state.source = planList(content);
    state.pager.total = totalElements;
    state.pager.current = page;
  }
};

onMounted(async () => {
  await getShipDict();
  await getDepts();
  getList(1);
});

const onExportExcel = () => {
  const { repairId, departId, type } = toRaw(state.searchObj);
  const shipOpts = _.find(state.formInputs, { name: "repairId" }).options;
  const deptOpts = _.find(state.formInputs, { name: "departId" }).options;

  let url = null;
  let name = "";
  if (type === 0) {
    url = "excel/export/solid";
    name = "使用材料";
  } else if (type === 1) {
    url = "excel/export/machine";
    name = "使用设备";
  }
  if (url && repairId && departId) {
    proxy.$axios
      .get(url, {
        params: { shipRepairId: repairId, departId },
        responseType: "blob",
      })
      .then((data) => {
        const shipName = _.find(shipOpts, { value: repairId }).label;
        const deptName = _.find(deptOpts, { value: departId }).label;

        const blobUrl = window.URL.createObjectURL(data);
        const link = document.createElement("a");
        link.href = blobUrl;
        link.download = `${shipName}_${deptName}_${name}.xlsx`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(blobUrl);
      });
  }
};
</script>

<style lang="less" scoped>
.innerBox {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .search {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
  }

  .tables {
    flex: 1;
    overflow-y: auto;
    background-color: #181818;
    padding: 2px;
  }
}
</style>
